/*
 日期：2025-05-30
 作者：lijj
 作用：测试消息中心数据统计功能[post]
*/

#include <iostream>
#include <string>
#if defined(_WIN32)
#include <Windows.h>
#include <process.h>
#else
#include <unistd.h>
#endif
#include <chrono>
#include "mgnotify.h"
#include "center.hpp"

using namespace std;
using namespace chrono;

typedef std::chrono::high_resolution_clock::time_point chpt;

class carrier : public BaseMessage<carrier>
{
public:
    string name;
    // 测试耗时: 开始时间
    chpt start_time;
};

class recv1 : public BaseHandle<carrier>
{
public:
    recv1() {}
    ~recv1() {}
    virtual bool handle(const carrier* msg) override;
};

void logo()
{
    cout << endl;
    cout << endl;
    cout << "  _________ __                        \n";  
    cout << " /   _____//  |_  ____   ____   ____     \n"; 
    cout << " \\_____  \\\\   __\\/  _ \\ /    \\_/ __ \\    \n"; 
    cout << " /        \\|  | (  <_> )   |  \\  ___/    \n"; 
    cout << "/_______  /|__|  \\____/|___|  /\\___  >  \n";
    cout << "        \\/                  \\/     \\/   \n";
    cout << endl;
    cout << endl;
}

void title()
{
    cout << endl;
    cout << "  日期：2025-05-30 \n";  
    cout << "  作者：lijj \n"; 
    cout << "  作用：测试消息中心数据统计功能[post] \n"; 
    cout << "  详情：统计发送者个数、发送者名称列表、发送者对应接受者个数 \n"; 
    cout << endl;
}

void enter()
{
    logo();
    title();
    while(true) {
        string in;
        cin >> in;
        cout << "enter: " << in << endl;
        if(in == "quit")
            break;
    }
}

void msgCount()
{
    cout << "sender count: " << mgnotify::getInstance()->senderCount() << endl;
    auto p = mgnotify::getInstance()->senders();
    for(auto it = p.begin(); it != p.end(); it++) {
        cout << "sender " << *it;

        cout << " has " << mgnotify::getInstance()->receiverCount(*it) << " receivers\n";
    }
}

int main()
{
#if defined(_WIN32 )
    SetConsoleOutputCP(65001); // UTF-8 
    SetConsoleCP(65001);       // 输入也设为UTF-8 
#endif 
    msgCount();
    thread t(enter);
#if defined(_WIN32)
    Sleep(100);
#else
    sleep(0.1);
#endif
    recv1 r1;
    msgCount();
    carrier m1;
    list<recv1*> rs1;
    int count = 10;
    for(int i = 0; i < count; i++) {
        recv1 *r1 = new recv1;
        rs1.push_back(r1);
    }
    msgCount();
    m1.start_time = high_resolution_clock::now();
    m1.name = "ljj";
    m1.post();
    t.join();
    
    while (!rs1.empty()) {
        auto t = rs1.back();
        rs1.pop_back();
        delete t;
        t = nullptr;
    }
    return 0;
}

bool recv1::handle(const carrier* msg)
{
    auto end = high_resolution_clock::now();
    std::chrono::duration<double, std::milli> elapsed = end - msg->start_time;
    cout << "carrier--> name: " << msg->name << ", 从开始发送消息到接受消息耗时： " << elapsed.count() << " ms." << endl;
    return true;
}